<template>
  <view class="publish-container">
    <!-- 顶部操作栏 -->
    <view class="header-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <text class="cancel-btn" @tap="onCancel">取消</text>
      <text class="title">发布动态</text>
    </view>

    <!-- 内容输入区 -->
    <scroll-view class="content-area" scroll-y>
      <!-- 作品类型选择 -->
      <view class="form-section">
        <view class="section-title">作品类型</view>
        <view class="category-selector" @tap="showCategoryPicker">
          <text class="category-label">选择类型</text>
          <text class="category-value">{{ categoryText }}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>

      <!-- 标题输入 -->
      <view class="form-section">
        <view class="section-title">作品标题</view>
        <input class="title-input" v-model="title" placeholder="请输入作品标题" placeholder-style="color: #999"
          maxlength="50" />
        <text class="word-count">{{ title.length }}/50</text>
      </view>

      <!-- 描述输入 -->
      <view class="form-section">
        <view class="section-title">作品描述</view>
        <textarea class="content-textarea" v-model="content" placeholder="分享你的生活..." placeholder-style="color: #999"
          maxlength="1000" :auto-height="true" />
        <text class="word-count">{{ content.length }}/1000</text>
      </view>

      <!-- 媒体选择 -->
      <view class="form-section">
        <view class="section-title">图片/视频</view>
      </view>
      <view class="media-section">
        <!-- 媒体类型选择 -->
        <view class="media-type-selector">
          <view class="media-type-btn" :class="{ active: mediaType === 'image' }" @tap="setMediaType('image')">
            <u-icon name="photo" size="18" :color="mediaType === 'image' ? '#4A90E2' : '#999'"></u-icon>
            <text class="media-type-text">图片</text>
          </view>
          <view class="media-type-btn" :class="{ active: mediaType === 'video' }" @tap="setMediaType('video')">
            <u-icon name="play-circle" size="18" :color="mediaType === 'video' ? '#4A90E2' : '#999'"></u-icon>
            <text class="media-type-text">视频</text>
          </view>
        </view>

        <!-- 图片列表 -->
        <view v-if="mediaType === 'image'" class="image-list">
          <view v-for="(img, index) in images" :key="index" class="image-item">
            <image class="preview-image" :src="img" mode="aspectFill"></image>
            <view class="delete-icon" @tap="deleteImage(index)">
              <text class="delete-text">×</text>
            </view>
          </view>
          <view v-if="images.length < 9" class="add-media-btn" @tap="chooseImage">
            <text class="add-icon">+</text>
            <text class="add-text">添加图片</text>
          </view>
        </view>

        <!-- 视频预览 -->
        <view v-if="mediaType === 'video'" class="video-preview">
          <view v-if="videoUrl" class="video-item">
            <video class="preview-video" :src="videoUrl" :poster="videoCover" controls :show-center-play-btn="false"
              :object-fit="'cover'" :enable-progress-gesture="true" @play="isVideoPlaying = true"
              @pause="isVideoPlaying = false" @ended="isVideoPlaying = false"></video>
            <view class="delete-icon" @tap="deleteVideo">
              <text class="delete-text">×</text>
            </view>
            <view v-if="!isVideoPlaying" class="video-play-icon">
              <u-icon name="play-circle-fill" size="40" color="#fff"></u-icon>
            </view>
          </view>
          <view v-else class="add-media-btn" @tap="chooseVideo">
            <text class="add-icon">+</text>
            <text class="add-text">添加视频</text>
          </view>
        </view>
      </view>

      <!-- 功能选项 -->
      <view class="options-section">
        <!-- 标签 -->
        <view class="option-item" @tap="showTagPicker">
          <text class="option-icon">🏷️</text>
          <text class="option-label">标签</text>
          <text class="option-value">{{ selectedTags.length > 0 ? selectedTags.join(' ') : '添加标签' }}</text>
        </view>

        <!-- 位置 -->
        <view class="option-item" @tap="chooseLocation">
          <text class="option-icon">📍</text>
          <text class="option-label">位置</text>
          <text class="option-value">{{ location || '添加位置' }}</text>
        </view>

        <!-- 可见范围 -->
        <view class="option-item" @tap="showVisibilityPicker">
          <text class="option-icon">👁️</text>
          <text class="option-label">可见范围</text>
          <text class="option-value">{{ visibility }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部固定操作栏 -->
    <view class="bottom-bar">
      <view class="draft-btn" @tap="onSaveDraft">
        <u-icon name="folder" size="20" color="#666"></u-icon>
        <text class="btn-text">存入草稿箱</text>
      </view>
      <view class="publish-btn-bottom" :class="{ disabled: !canPublish }" @tap="onPublish">
        <u-icon name="arrow-up" size="20" color="#fff"></u-icon>
        <text class="btn-text">发布作品</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { createWork, uploadFile, WorkStatusEnum, MediaTypeEnum, WorkCategoryEnum } from '@/api/works'
import { TOKEN_KEY } from '@/config/env'

// 检查是否登录
const checkLogin = (): boolean => {
  const token = uni.getStorageSync(TOKEN_KEY)
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }, 1500)
    return false
  }
  return true
}

// 系统信息
const statusBarHeight = ref(0)

// 内容
const title = ref('')
const content = ref('')
const images = ref<string[]>([])
const videoUrl = ref('')
const videoCover = ref('')
const isVideoPlaying = ref(false)
const mediaType = ref<'image' | 'video'>('image')
const category = ref<'food' | 'health' | 'travel'>('food')
const selectedMood = ref('')
const selectedTags = ref<string[]>([])
const location = ref('')
const visibility = ref('公开')

// 作品类型映射
const categoryMap = {
  food: '美食',
  health: '养生',
  travel: '旅游'
}

// 作品类型显示文本
const categoryText = computed(() => {
  return categoryMap[category.value] || '美食'
})

// 获取系统信息
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
})

// 是否可以发布
const canPublish = computed(() => {
  return (title.value.trim().length > 0 || content.value.trim().length > 0) || images.value.length > 0 || videoUrl.value.length > 0
})

// 设置媒体类型
const setMediaType = (type: 'image' | 'video') => {
  if (mediaType.value !== type) {
    // 切换类型时清空之前的内容
    if (type === 'image') {
      videoUrl.value = ''
      videoCover.value = ''
      isVideoPlaying.value = false
    } else {
      images.value = []
    }
    mediaType.value = type
  }
}

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - images.value.length,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      images.value = [...images.value, ...res.tempFilePaths]
    }
  })
}

// 删除图片
const deleteImage = (index: number) => {
  images.value.splice(index, 1)
}

// 选择视频
const chooseVideo = () => {
  uni.chooseVideo({
    sourceType: ['album', 'camera'],
    maxDuration: 60, // 最长60秒
    camera: 'back',
    success: (res) => {
      videoUrl.value = res.tempFilePath
      // 视频封面图（如果存在）
      videoCover.value = (res as any).thumbTempFilePath || res.tempFilePath
      isVideoPlaying.value = false
    },
    fail: (err) => {
      console.error('选择视频失败:', err)
      uni.showToast({
        title: '选择视频失败',
        icon: 'none'
      })
    }
  })
}

// 删除视频
const deleteVideo = () => {
  videoUrl.value = ''
  videoCover.value = ''
  isVideoPlaying.value = false
}

// 显示作品类型选择器
const showCategoryPicker = () => {
  uni.showActionSheet({
    itemList: ['美食', '养生', '旅游'],
    success: (res) => {
      const categories: ('food' | 'health' | 'travel')[] = ['food', 'health', 'travel']
      category.value = categories[res.tapIndex]
    }
  })
}

// 显示心情选择器
const showMoodPicker = () => {
  uni.showActionSheet({
    itemList: ['开心 😊', '难过 😢', '兴奋 😆', '平静 😌', '感动 🥺'],
    success: (res) => {
      const moods = ['开心 😊', '难过 😢', '兴奋 😆', '平静 😌', '感动 🥺']
      selectedMood.value = moods[res.tapIndex]
    }
  })
}

// 显示标签选择器
const showTagPicker = () => {
  uni.showModal({
    title: '添加标签',
    editable: true,
    placeholderText: '输入标签，用空格分隔',
    success: (res) => {
      if (res.confirm && res.content) {
        selectedTags.value = res.content.trim().split(/\s+/)
      }
    }
  })
}

// 选择位置
const chooseLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      location.value = res.name || res.address
    }
  })
}

// 显示可见范围选择器
const showVisibilityPicker = () => {
  uni.showActionSheet({
    itemList: ['公开', '仅好友可见', '仅自己可见'],
    success: (res) => {
      const options = ['公开', '仅好友可见', '仅自己可见']
      visibility.value = options[res.tapIndex]
    }
  })
}

// 取消发布
const onCancel = () => {
  if (title.value || content.value || images.value.length > 0 || videoUrl.value) {
    uni.showModal({
      title: '提示',
      content: '是否放弃本次编辑？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack()
        }
      }
    })
  } else {
    uni.navigateBack()
  }
}

// 上传所有媒体文件
const uploadMediaFiles = async (): Promise<{ imagesUrls?: string[], videoUrl?: string, videoCover?: string }> => {
  const result: { imagesUrls?: string[], videoUrl?: string, videoCover?: string } = {}

  if (mediaType.value === 'image' && images.value.length > 0) {
    // 上传图片
    uni.showLoading({ title: '上传图片中...', mask: true })
    try {
      const uploadPromises = images.value.map(img => uploadFile(img, 'image'))
      result.imagesUrls = await Promise.all(uploadPromises)
      uni.hideLoading()
    } catch (error: any) {
      uni.hideLoading()
      throw new Error(error.message || '图片上传失败')
    }
  } else if (mediaType.value === 'video' && videoUrl.value) {
    // 上传视频
    uni.showLoading({ title: '上传视频中...', mask: true })
    try {
      result.videoUrl = await uploadFile(videoUrl.value, 'video')
      // 如果有视频封面，也上传
      if (videoCover.value) {
        result.videoCover = await uploadFile(videoCover.value, 'image')
      }
      uni.hideLoading()
    } catch (error: any) {
      uni.hideLoading()
      throw new Error(error.message || '视频上传失败')
    }
  }

  return result
}

// 保存草稿
const onSaveDraft = async () => {
  if (!checkLogin()) {
    return
  }

  // 验证必填项
  if (!title.value.trim() && !content.value.trim() && images.value.length === 0 && !videoUrl.value) {
    uni.showToast({
      title: '请填写标题、描述或添加媒体',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({ title: '保存中...', mask: true })

    // 上传媒体文件
    const mediaFiles = await uploadMediaFiles()

    // 组装数据
    const workData = {
      title: title.value.trim() || '无标题',
      description: content.value.trim() || '',
      category: category.value as WorkCategoryEnum,
      status: WorkStatusEnum.DRAFT,
      isPublic: visibility.value === '公开',
      mediaType: mediaType.value === 'image' ? MediaTypeEnum.IMAGE : MediaTypeEnum.VIDEO,
      tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
      location: location.value || undefined,
      ...mediaFiles
    }

    // 调用API创建作品
    await createWork(workData)

    uni.hideLoading()
    uni.showToast({
      title: '已保存到草稿箱',
      icon: 'success'
    })

    // 清空表单
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error: any) {
    uni.hideLoading()
    console.error('保存草稿失败:', error)
    uni.showToast({
      title: error.message || '保存失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

// 发布
const onPublish = async () => {
  if (!canPublish.value) {
    return
  }

  if (!checkLogin()) {
    return
  }

  // 验证必填项
  if (!title.value.trim() && !content.value.trim() && images.value.length === 0 && !videoUrl.value) {
    uni.showToast({
      title: '请填写标题、描述或添加媒体',
      icon: 'none'
    })
    return
  }

  // 验证媒体文件
  if (mediaType.value === 'image' && images.value.length === 0) {
    uni.showToast({
      title: '请至少添加一张图片',
      icon: 'none'
    })
    return
  }

  if (mediaType.value === 'video' && !videoUrl.value) {
    uni.showToast({
      title: '请添加视频',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({ title: '发布中...', mask: true })

    // 上传媒体文件
    const mediaFiles = await uploadMediaFiles()

    // 组装数据
    const workData = {
      title: title.value.trim() || '无标题',
      description: content.value.trim() || '',
      category: category.value as WorkCategoryEnum,
      status: WorkStatusEnum.PUBLISHED,
      isPublic: visibility.value === '公开',
      mediaType: mediaType.value === 'image' ? MediaTypeEnum.IMAGE : MediaTypeEnum.VIDEO,
      tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
      location: location.value || undefined,
      ...mediaFiles
    }

    // 调用API创建作品
    await createWork(workData)

    uni.hideLoading()
    uni.showToast({
      title: '发布成功',
      icon: 'success'
    })

    // 清空表单并返回
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/home/home'
      })
    }, 1500)
  } catch (error: any) {
    uni.hideLoading()
    console.error('发布失败:', error)
    uni.showToast({
      title: error.message || '发布失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}
</script>

<style scoped>
.publish-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部操作栏 */
.header-bar {
  background-color: #fff;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20rpx 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
  z-index: 1;
}

.cancel-btn {
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  color: #666;
}

.title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 内容区域 */
.content-area {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 120rpx;
  /* 为底部按钮留出空间 */
}

/* 表单区域 */
.form-section {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
  position: relative;
}

.form-section:first-child {
  margin-top: 0;
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

/* 作品类型选择器 */
.category-selector {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.category-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.category-value {
  flex: 1;
  font-size: 28rpx;
  color: #666;
  text-align: right;
  margin-right: 10rpx;
}

/* 标题输入 */
.title-input {
  width: 100%;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
}

/* 描述输入 */
.content-textarea {
  width: 100%;
  min-height: 300rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  padding: 20rpx 0;
}

.word-count {
  position: absolute;
  bottom: 20rpx;
  right: 30rpx;
  font-size: 22rpx;
  color: #999;
}

/* 媒体区域 */
.media-section {
  background-color: #fff;
  padding: 0 30rpx 30rpx 30rpx;
}

/* 媒体类型选择器 */
.media-type-selector {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.media-type-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  background-color: #f5f5f5;
  transition: all 0.3s;
}

.media-type-btn.active {
  background-color: #E8F4FD;
}

.media-type-text {
  font-size: 26rpx;
  color: #666;
}

.media-type-btn.active .media-type-text {
  color: #4A90E2;
  font-weight: 500;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  width: 200rpx;
  height: 200rpx;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.delete-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-text {
  color: #fff;
  font-size: 32rpx;
  line-height: 1;
}

.add-media-btn {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

/* 视频预览 */
.video-preview {
  width: 100%;
}

.video-item {
  position: relative;
  width: 100%;
  height: 400rpx;
  border-radius: 10rpx;
  overflow: hidden;
  background-color: #000;
}

.preview-video {
  width: 100%;
  height: 100%;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  pointer-events: none;
}

.add-icon {
  font-size: 60rpx;
  color: #999;
}

.add-text {
  font-size: 24rpx;
  color: #999;
}

/* 功能选项 */
.options-section {
  background-color: #fff;
  margin-top: 20rpx;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.option-item:last-child {
  border-bottom: none;
}

.option-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.option-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.option-value {
  flex: 1;
  font-size: 26rpx;
  color: #999;
  text-align: right;
}

.option-arrow {
  font-size: 24rpx;
  color: #ccc;
  margin-left: 10rpx;
}

/* 底部固定操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  z-index: 100;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.draft-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx 40rpx;
  border: 1rpx solid #ddd;
  border-radius: 50rpx;
  background-color: #fff;
  transition: all 0.3s;
}

.draft-btn:active {
  background-color: #f5f5f5;
  transform: scale(0.98);
}

.publish-btn-bottom {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx 40rpx;
  border-radius: 50rpx;
  background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
  color: #fff;
  transition: all 0.3s;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
}

.publish-btn-bottom:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(74, 144, 226, 0.3);
}

.publish-btn-bottom.disabled {
  background: #ccc;
  box-shadow: none;
  opacity: 0.6;
}

.publish-btn-bottom.disabled:active {
  transform: none;
}

.btn-text {
  font-size: 28rpx;
  font-weight: 500;
}
</style>
